﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MovieRental.Entities;
using MovieRental.DataInterfaces;
using MovieRental.BuisnessComponents.Exceptions;


namespace MovieRental.BuisnessComponents.Base
{
    public abstract class BaseSetComponent<TEntity, TKey, IRepository> : BaseComponent<TEntity, TKey, IRepository>
        where IRepository : IRepository<TEntity, TKey>
        where TEntity : BaseEntity<TKey>
        where TKey : IEquatable<TKey>
    {
        public BaseSetComponent(IRepository repo)
            :base(repo)
        {
        }

        protected abstract bool Equals(TEntity obj1, TEntity obj2);

        protected virtual TEntity FindSimilar(TEntity obj)
        {
            var similar = Repository.LoadAll().SingleOrDefault(x => Equals(obj, x));
            if (similar == null)
                return null;
            return (!similar.Id.Equals(obj.Id)) ? similar : null;
        }

        public override void Verify(TEntity obj)
        {
            var similar = FindSimilar(obj);
            if (similar != null)
                throw new ItemDuplicateException<TKey>(obj, similar);
        }
    }
}
